﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Mysqlx;
using Newtonsoft.Json;
using ServiceStack;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Configuration;
using System.Linq;
using System.Linq.Expressions;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using ZH.Infrastructure.Attr;
using ZH.Infrastructure.Dto.Request.Login;
using ZH.Infrastructure.Dto.Request.Tech;
using ZH.Infrastructure.Dto.Request.Yuyue;
using ZH.Infrastructure.Dto.Response;
using ZH.Infrastructure.Dto.Response.admin;
using ZH.Infrastructure.Dto.Response.Yuyue;
using ZH.Infrastructure.EFCore.MySql;
using ZH.Infrastructure.IOC;
using ZH.Infrastructure.Redis;
using ZH.Infrastructure.Tools;
using ZH.Service.Interface;

namespace ZH.Service.Instance
{
    [Inject_]
    public class Yuyue_Service : Base_Service, I_Yuyue_Service
    {
        private readonly Mobile_IOC _mobile_IOC;
        private readonly Tech_IOC _tech_IOC;
        private readonly Emp_IOC _emp_IOC;
        private readonly Room_IOC _room_IOC;
        private readonly Yuyue_IOC _yuyue_IOC;
        private readonly Order_IOC _order_IOC;
        private readonly IConfiguration _configuration;
        public Yuyue_Service(Order_IOC order_IOC,Tech_IOC tech_IOC,Emp_IOC emp_IOC,Room_IOC room_IOC, Mobile_IOC mobile_IOC,Yuyue_IOC yuyue_IOC, IConfiguration configuration)
        {
            _mobile_IOC = mobile_IOC;
            _tech_IOC = tech_IOC;
            _emp_IOC = emp_IOC;
            _room_IOC = room_IOC;
            _yuyue_IOC = yuyue_IOC;
            _order_IOC = order_IOC;
            _configuration = configuration;
        }

        public async Task<Api_Response_Dto> ADD_App(Appointment dto)
        {
            _mobile_IOC._yuyue_EFCore.Add(dto);
            var code = await _mobile_IOC._yuyue_EFCore.SaveChangesAsync();
            return Result(1, "添加成功");
        }

        /// <summary>
        /// 获取服务
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Response_Dto> Get_Service(int? page, int? limit, string? id)
        {
            var data = await _tech_IOC._tech_Service.QueryAll(out int total,
                    Convert.ToInt32(page),
                    Convert.ToInt32(limit),
                    true, o => o.TechId, d => d.TechType == id
                    ).ToListAsync();
            return Result(1, "ok", new { data, total });
        }

        /// <summary>
        /// 获取服务类型
        /// </summary>
        /// <returns></returns>
        public async Task<Api_Response_Dto> Get_Service_Type()
        {
            var type = _configuration["Dictionary_Type:Tech"];
            if (string.IsNullOrEmpty(type))
            {
                return Result(0, "参数有误");
            }
            var data = await _mobile_IOC._dictionary_EFCore
                .QueryAll(d => d.DparentId == type && d.DisBan == 0)
                .Select(d => new Yuyue_Response_Dto
                {
                    did = d.Did,
                    name = d.Dname,
                    isban = d.DisBan,
                    parent = d.DparentId
                }).ToListAsync();
            return Result(1, "ok", data);
        }


        public async Task<Api_Response_Dto> Get_order(User_Response_Dto? yy, string type)
        {
            var ls = await _mobile_IOC._yuyue_EFCore.QueryAll(d => d.Status == type && d.MId == yy.id).ToListAsync();
            var service = _mobile_IOC._tech_EFCore.QueryAll().ToList();
           
            var data = from s in service
                       join l in ls 
                       on s.TechId equals l.ServiceId
                       select new Appointment_Response_Dto
                       {
                           aId = l.Aid,
                           appointmentdate = l.AppointmentDate,
                           start_time = l.StartTime,
                           service_item = l.ServiceItem,
                           status = l.Status,
                           notes = l.Notes,
                           created_at = l.CreatedAt.ToString(),
                           tech_duration =s.TechDuration.ToString(),
                           tech_price =s.TechPrice.ToString(),
                           img=s.TechImg
                       };


            return Result(1,"ok",data);
        }

        public async Task<Api_Response_Dto> Cancel_order(Yuyue_Request_Dto dto) 
        {
            var order = await _mobile_IOC._yuyue_EFCore.QueryAll(d => d.Aid == dto.M_id && d.Status == "待处理").SingleOrDefaultAsync();
            if (order == null) 
            {
                return Result(0, "预约有误");
            }
            if (dto.Status == "待处理") 
            {
                order.Status = "已取消";
            }
            else
            {
                order.Status = "待处理";
            }
            _mobile_IOC._yuyue_EFCore.Update(order);
            var result = await _mobile_IOC._yuyue_EFCore.SaveChangesAsync();
            return Result(result);

        }

        public async Task<Api_Response_Dto> Get_Cashier_Appointment()
        {
            var data = await _yuyue_IOC._yuyue_EFCore.QueryAll().ToListAsync();

            var mobile = await _mobile_IOC._mobile_EFCore.QueryAll().ToListAsync();

            var tech = await _tech_IOC._tech_Service.QueryAll().ToListAsync();

            

            var appointment = from a in data
                              select new Cashier_Yuyue_Response_Dto
                              {
                                  id = 0,
                                  appointmentNo = a.Aid,
                                  customerName = a.CustomerName,
                                  customerPhone = a.CustomerPhone,
                                  isMember = mobile.Where(m => m.Mphone == a.CustomerPhone).Count() > 0 ? true : false,
                                  memberLevel = mobile.Where(m => m.Mphone == a.CustomerPhone).Count() > 0 ? mobile.Where(m => m.Mphone == a.CustomerPhone).FirstNonDefault().MemberLevel : "",
                                  service = a.ServiceItem,
                                  duration = tech.Where(t => t.TechId == a.ServiceId).FirstNonDefault().TechDuration + "分钟",
                                  price = "¥" + tech.Where(t => t.TechId == a.ServiceId).FirstNonDefault().TechPrice,
                                  bookingDate = a.AppointmentDate,
                                  status = a.Status,
                                  staff = "",
                                  createTime = a.CreatedAt.ToString(),
                                  notes = a.Notes
                              };

            // 将查询结果转换为列表以便修改
            var list = appointment.ToList();

            // 为每个元素分配自增ID
            int currentId = 1;
            foreach (var item in list)
            {
                item.id = currentId++;
            }

            var count = list.Count();

            if (count > 0)
            {
                return Result(1, "ok", new { data = list, total = count });
            }
            else {

                return Result(0);
            }

        }

        public async Task<Api_Response_Dto> Get_Cashier_Emp()
        {
            var emp = await _emp_IOC._emp_EFCore.QueryAll(e => e.WorkStatus == "空闲").ToListAsync();

            if (emp.Count() > 0)
            {
                return Result(1, "ok", emp);
            }
            else { 
                return Result(0);
            }
        }

        public async Task<Api_Response_Dto> Get_Cashier_Room()
        {
            var room = await _room_IOC._room_EFCore.QueryAll( r => r.Rostart == "空闲").ToListAsync();

            if (room.Count() > 0)
            {
                return Result(1, "ok", room);
            }
            else
            {
                return Result(0);
            }
        }

        public async Task<Api_Response_Dto> Get_Cashier_Tech()
        {
            var tech = await _tech_IOC._tech_Service.QueryAll().ToListAsync();

            if (tech.Count() > 0)
            {
                return Result(1, "ok", tech);
            }
            else
            {
                return Result(0);
            }
        }

        public async Task<Api_Response_Dto> Cashier_Order_Appointment(Yuyue_Cashier_Request_Dto dto)
        {
            var appoint = await _yuyue_IOC._yuyue_EFCore.QueryAll(a => a.Aid == dto.aid).FirstOrDefaultAsync();

            var room = await _room_IOC._room_EFCore.QueryAll( r => r.Roid == dto.rid ).FirstOrDefaultAsync();

            var emp = await _emp_IOC._emp_EFCore.QueryAll(e => e.EmpId == dto.eid).FirstOrDefaultAsync();

            var tech = await _tech_IOC._tech_Service.QueryAll(t => t.TechId == appoint.ServiceId).FirstOrDefaultAsync();

            var mobile = await _mobile_IOC._mobile_EFCore.QueryAll(m => m.Mphone == appoint.CustomerPhone).FirstOrDefaultAsync();


            Order order = new Order()
            {
                OrId = dto.aid!,
                OrCreatTime = DateTime.Now,
                OrMid = appoint!.MId,
                OrMoney = decimal.Parse(tech.TechPrice.ToString()),
                OrPayment = "",
                Emid = dto.eid,
                Roid = dto.rid,
                OrStatus = 2,
                DiscountPrice = decimal.Parse(tech.TechPrice.ToString())
            };

            _order_IOC._order_EFCore.Add(order);

            var count = await _order_IOC._order_EFCore.SaveChangesAsync();


            if (count > 0)
            {
                Orderdetail detail = new Orderdetail()
                {
                    Odid = Config.GUID(),
                    OrId = dto.aid!,
                    OdName = tech.TechName,
                    OdDuration = tech.TechDuration,
                    OdMoney = double.Parse(tech.TechPrice.ToString()),
                    OdCreateTime = DateTime.Now,
                };

                _order_IOC._orderdetail_EFCore.Add(detail);

                await _order_IOC._orderdetail_EFCore.SaveChangesAsync();

                emp.WorkStatus = "忙碌";

                room.Rostart = "使用中";

                _emp_IOC._emp_EFCore.Update(emp);

                _room_IOC._room_EFCore.Update(room);

                await _emp_IOC._emp_EFCore.SaveChangesAsync();

                await _room_IOC._room_EFCore.SaveChangesAsync();

                appoint.Status = "已确认";

                _yuyue_IOC._yuyue_EFCore.Update(appoint);

                await _yuyue_IOC._yuyue_EFCore.SaveChangesAsync();

                return Result(1, "ok");
            }
            else {
                return Result(0);
            }
            
        }
    }
}